package com.nowcoder.Offer.Array;

import org.junit.Test;

import java.util.ArrayList;

/**
 * 打印旋转矩阵
 */
public class printMatrix {
    public ArrayList<Integer> printMatrix(int [][] matrix) {
        if(matrix == null || matrix.length == 0 ) return new ArrayList<>();
        int n = matrix.length, m = matrix[0].length;
        int l = 0, r = m-1, t = 0, b = n - 1;
        ArrayList<Integer> ans = new ArrayList<>();
        while(true){
            for(int i = l; i<=r; i++) ans.add(matrix[t][i]);
            if(++t > b) break;
            for(int i = t; i<=b; i++) ans.add(matrix[i][r]);
            if(--r < l) break;
            for(int i = r; i>=l; i--) ans.add(matrix[b][i]);
            if(--b < t) break;
            for(int i = b; i>=t; i--) ans.add(matrix[i][l]);
            if(++l > r) break;
        }
        return ans;
    }

    @Test
    public void test(){
        int[][] matrix = {
                {1,2,3,4},
                {5,6,7,8},
                {9,10,11,12},
                {13,14,15,16}
        };
        printMatrix(matrix).forEach(e -> System.out.print(e+" "));
    }
}
